﻿using UnityEngine;
using System.Collections;

public class CharacterControl : MonoBehaviour {

	public float maxSpeed=10f;
	public float jumpForce=20f;
	public Transform GroundChecker;
	public LayerMask groundMask;
	public Transform UpperFaceCheck;
	public Transform LowerFaceCheck;

	private Animator animator;
	private Rigidbody2D body;
	private bool facingRight =true;
	private bool Grounded=false;
	private bool BlockedTop=false;
	private bool BlockedBot=false;


	// Use this for initialization
	void Start () {
		animator=this.GetComponent<Animator>();
		body=this.GetComponent<Rigidbody2D>();
		 
	}
	
	// Update is called once per frame
	void Update () {
		if(Input.GetAxis("A")>0&&Grounded){

			Grounded=false;
			body.AddForce(new Vector2(0,jumpForce),ForceMode2D.Impulse);
			animator.SetFloat("vSpeed",body.velocity.x);

		}

	}

	void FixedUpdate(){
		//body.transform.Translate(new Vector2(0,0.01f));
		BlockedTop= Physics2D.OverlapPoint(UpperFaceCheck.position,groundMask);
		BlockedBot= Physics2D.OverlapPoint(LowerFaceCheck.position,groundMask);
		Grounded= Physics2D.OverlapCircle(GroundChecker.position,0.1f,groundMask);	

		animator.SetBool("InAir",!Grounded);
		var moveSpeed=Input.GetAxis("Horizontal");
		body.velocity= new Vector2(moveSpeed*maxSpeed,body.velocity.y);		
		ChangeFacingDirection ();


		if( !BlockedTop && !BlockedBot){
			animator.SetFloat("Speed",Mathf.Abs( body.velocity.magnitude));
		}
		else animator.SetFloat("Speed",0);
	
		
	}


	void ChangeFacingDirection ()
	{
		var theScale = this.transform.localScale;
		if (Input.GetAxis ("Horizontal") > 0 && !facingRight) {
			theScale.x = -theScale.x;
			this.transform.localScale = theScale;
			facingRight = true;
		}
		else
			if (Input.GetAxis ("Horizontal") < 0 && facingRight) {
				facingRight = false;
				theScale.x = -theScale.x;
				this.transform.localScale = theScale;
			}
	}
}
